
import cv2
import matplotlib.pyplot as plt
from ultralytics import YOLO
import numpy as np

# 读取图像，以灰度模式读取
image = cv2.imread('test.png')
model = YOLO('../ultralytics/assets/yolo11n.pt')
# 使用 YOLOv8 进行目标检测
# 这种方式不支持灰度图像 需要使用三通道的彩色图像
results = model(image)

# 获取检测到的人的边界框
person_boxes = []
for result in results:
    boxes = result.boxes
    for box in boxes:
        if int(box.cls[0]) == 0:  # 类别 0 表示人
            person_boxes.append(box.xyxy[0].cpu().numpy().astype(int))

# 对每个人的区域进行轮廓提取


# 获取检测到的人的边界框
person_boxes = []
for result in results:
    boxes = result.boxes
    for box in boxes:
        if int(box.cls[0]) == 0:  # 类别 0 表示人
            person_boxes.append(box.xyxy[0].cpu().numpy().astype(int))

# 对每个人的区域进行轮廓提取
for i, box in enumerate(person_boxes):
    x1, y1, x2, y2 = box
    person_image = image[y1:y2, x1:x2]
    # 图像灰度处理
    gray_person = cv2.cvtColor(person_image, cv2.COLOR_BGR2GRAY)

    # # 高斯模糊，减少噪声
    blurred = cv2.GaussianBlur(gray_person, (5, 5), 0)

    # # 展示高斯模糊后的图像
    # plt.figure(figsize=(5, 5))
    # plt.imshow(blurred, cmap='gray')
    # plt.title(f'Gaussian Blurred Image of Person {i + 1}')
    # plt.axis('off')
    # plt.show()

    # 直方图均衡化
    equalized_gray_person = cv2.equalizeHist(blurred)

    # 展示直方图均衡化后的图像
    plt.figure(figsize=(5, 5))
    plt.imshow(equalized_gray_person, cmap='gray')
    plt.title(f'Histogram Equalized Image of Person {i + 1}')
    plt.axis('off')
    plt.show()

    # Canny 边缘检测，尝试调整阈值
    edges = cv2.Canny(equalized_gray_person, 100, 300)

    # 查找轮廓
    contours, _ = cv2.findContours(edges.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # 在原始图像上绘制人的轮廓
    for contour in contours:
        contour[:, :, 0] += x1
        contour[:, :, 1] += y1
        cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)

    # 在图像上绘制人区域的矩形框
    cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)

    # 遍历显示轮廓范围
    print(f"Person {i + 1} Contour Range: x1={x1}, y1={y1}, x2={x2}, y2={y2}")

# 显示带有轮廓和人区域矩形框的图像
plt.figure(figsize=(10, 10))
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Person Contours and Regions')
plt.axis('off')
plt.show()
    